from functools import wraps
from django.utils.decorators import available_attrs
from django.http import JsonResponse
from apps.sales_man.models import SalesMan
from core.tools.encryption import md5


def authentication():
    def decorator(view_func):
        """django.contrib.auth.decorators重写"""

        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            account = request.POST.get("account")
            password = request.POST.get("password")
            child_account = request.GET.get("child_account")
            if not account or not password:
                return JsonResponse({"message": "请填写账号和密码"})
            password = md5(md5(password))
            try:
                salesman = SalesMan.objects.get(account=account, password=password)
                request.salesman = salesman
                if child_account:
                    try:
                        child_salesman = SalesMan.objects.get(account=child_account, leader=salesman)
                        request.child_salesman = child_salesman
                        return view_func(request, *args, **kwargs)
                    except Exception as e:
                        print(e)
                    return JsonResponse({"message": "此子账号不属于您的下级"})
                return view_func(request, *args, **kwargs)
            except Exception as e:
                print(e)
                return JsonResponse({"message": "账号密码错误"})

        return _wrapped_view

    return decorator
